package com.example.autoclick2;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FloatWindow {
    private Context context;
    private WindowManager windowManager;
    private View floatView;
    private WindowManager.LayoutParams params;
    
    private boolean isPickingCoordinate = false;
    private TextView tvCoordinate, tvMode;
    private Button btnStartStop, btnPickCoordinate;
    
    private int initialX, initialY;
    private float touchX, touchY;
    
    public FloatWindow(Context context) {
        this.context = context;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        initFloatWindow();
    }
    
    private void initFloatWindow() {
        // 创建悬浮窗布局
        floatView = LayoutInflater.from(context).inflate(R.layout.float_window, null);
        
        // 初始化控件
        tvCoordinate = floatView.findViewById(R.id.tv_coordinate);
        tvMode = floatView.findViewById(R.id.tv_mode);
        btnStartStop = floatView.findViewById(R.id.btn_start_stop);
        btnPickCoordinate = floatView.findViewById(R.id.btn_pick_coordinate);
        
        // 设置窗口参数
        params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.format = PixelFormat.TRANSLUCENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.gravity = Gravity.TOP | Gravity.START;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.x = 0;
        params.y = 100;
        
        // 设置悬浮窗可拖动
        LinearLayout rootLayout = floatView.findViewById(R.id.root_layout);
        rootLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isPickingCoordinate) {
                    return false;
                }
                
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = params.x;
                        initialY = params.y;
                        touchX = event.getRawX();
                        touchY = event.getRawY();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        params.x = initialX + (int) (event.getRawX() - touchX);
                        params.y = initialY + (int) (event.getRawY() - touchY);
                        windowManager.updateViewLayout(floatView, params);
                        return true;
                }
                return false;
            }
        });
        
        // 设置启动/停止按钮点击事件
        btnStartStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AutoClickService.isServiceRunning()) {
                    AutoClickService service = AutoClickService.getInstance();
                    if (service != null) {
                        if (btnStartStop.getText().toString().equals("开始")) {
                            service.startClick();
                            btnStartStop.setText("停止");
                        } else {
                            service.stopClick();
                            btnStartStop.setText("开始");
                        }
                    } else {
                        Toast.makeText(context, "无障碍服务未运行", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "请先开启无障碍服务", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        // 设置拾取坐标按钮点击事件
        btnPickCoordinate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPickingCoordinate) {
                    isPickingCoordinate = false;
                    btnPickCoordinate.setText("拾取坐标");
                    hideOverlay(); // 隐藏覆盖层
                    Toast.makeText(context, "已退出坐标拾取模式", Toast.LENGTH_SHORT).show();
                } else {
                    isPickingCoordinate = true;
                    btnPickCoordinate.setText("退出拾取");
                    showOverlay(); // 显示覆盖层
                    Toast.makeText(context, "已进入坐标拾取模式，点击屏幕任意位置获取坐标", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        // 创建全屏透明覆盖层用于拾取坐标
        createCoordinatePickerOverlay();
        
        // 初始化模式显示
        updateModeDisplay();
    }
    
    // 创建用于拾取坐标的全屏透明覆盖层
    private View overlayView;
    private WindowManager.LayoutParams overlayParams;
    
    private void createCoordinatePickerOverlay() {
        overlayView = new View(context);
        overlayParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            overlayParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            overlayParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        overlayParams.format = PixelFormat.TRANSLUCENT;
        // 修改标志，允许触摸事件穿透到下层窗口，只在拾取坐标模式下才捕获触摸事件
        overlayParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | 
                             WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                             WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                             WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        overlayParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        overlayParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        overlayParams.gravity = Gravity.CENTER;
        
        overlayView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!isPickingCoordinate) {
                    return false;
                }
                
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getRawX();
                    int y = (int) event.getRawY();
                    
                    // 更新坐标显示
                    tvCoordinate.setText("坐标: (" + x + ", " + y + ")");
                    
                    // 设置点击坐标
                    if (AutoClickService.isServiceRunning()) {
                        AutoClickService service = AutoClickService.getInstance();
                        if (service != null) {
                            service.setClickPosition(x, y);
                        }
                    }
                    
                    // 退出拾取模式
                    isPickingCoordinate = false;
                    btnPickCoordinate.setText("拾取坐标");
                    hideOverlay(); // 立即隐藏覆盖层
                    
                    return true;
                }
                return false;
            }
        });
    }
    
    // 显示悬浮窗
    public void show() {
        if (floatView.getWindowToken() == null && floatView.getParent() == null) {
            windowManager.addView(floatView, params);
            // 不再默认添加覆盖层，只在需要时添加
        }
    }
    
    // 显示覆盖层
    public void showOverlay() {
        try {
            if (overlayView.getWindowToken() == null && overlayView.getParent() == null) {
                windowManager.addView(overlayView, overlayParams);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 隐藏覆盖层
    public void hideOverlay() {
        try {
            if (overlayView.getWindowToken() != null || overlayView.getParent() != null) {
                windowManager.removeView(overlayView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 隐藏悬浮窗
    public void hide() {
        if (floatView.getWindowToken() != null || floatView.getParent() != null) {
            windowManager.removeView(floatView);
        }
        
        hideOverlay();
    }
    
    // 更新模式显示
    public void updateModeDisplay() {
        if (AutoClickService.isServiceRunning()) {
            AutoClickService service = AutoClickService.getInstance();
            if (service != null) {
                int mode = service.getClickMode();
                String modeText;
                
                switch (mode) {
                    case 0:
                        modeText = "单击";
                        break;
                    case 1:
                        modeText = "双击";
                        break;
                    case 2:
                        modeText = "上滑";
                        break;
                    case 3:
                        modeText = "下滑";
                        break;
                    default:
                        modeText = "单击";
                        break;
                }
                
                tvMode.setText("模式: " + modeText);
            }
        }
    }
    
    // 设置点击模式
    public void setClickMode(int mode) {
        if (AutoClickService.isServiceRunning()) {
            AutoClickService service = AutoClickService.getInstance();
            if (service != null) {
                service.setClickMode(mode);
                updateModeDisplay();
            }
        }
    }
}